package selef.xiafan.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import selef.xiafan.entity.user.User;
import selef.xiafan.service.ISysPermissionService;
import selef.xiafan.service.IUserService;

import java.util.Set;

/*
 * 自定义认证
 * Custom authenticator.Custom authorization and authentication
 * */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    IUserService iUserService;
    @Autowired
    ISysPermissionService iSysPermissionService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户权限
        String username = principalCollection.getPrimaryPrincipal().toString();
        Set<String> permissions = iSysPermissionService.listPermissionURLsByUser(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    // 登录用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取令牌
        String username = authenticationToken.getPrincipal().toString();
        // 获取用户信息
        User user = iUserService.getByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UnknownAccountException();
        }
        String password = user.getPassword();
        String salt = user.getSalt();
        // 认证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), getName());
        return simpleAuthenticationInfo;
    }
}
